//
//  TRBuyCarViewController.m
//  WeiMiLan
//
//  Created by anan on 15/8/3.
//  Copyright (c) 2015年 Mac. All rights reserved.
//

#import "TROrderDetailViewController.h"

@interface TROrderDetailViewController ()
{
    MJRefreshHeaderView *refreshHeaderView;
    MJRefreshFooterView *refreshFooterView;
}
@end

@implementation TROrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigation];
    self.contents = [[NSMutableArray alloc] init];
    
    UINib *nib1 = [UINib nibWithNibName:@"TROrderDetailTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"TROrderDetailTableViewCell"];
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.orderDetailFootView = [[[NSBundle mainBundle] loadNibNamed:@"TROrderDetailFootView" owner:self options:nil] lastObject];
    self.tableView.tableFooterView = self.orderDetailFootView;
    
    self.addressTableViewCell = [[[NSBundle mainBundle] loadNibNamed:@"TRAddressTableViewCell" owner:self options:nil] lastObject];
    self.addressTableViewCell.viewController = self;
    self.tableView.tableHeaderView = self.addressTableViewCell;
    
    [self addHeader];
    
    [refreshHeaderView beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refresh {
    [refreshHeaderView beginRefreshing];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view addSubview:self.weChatNavigationBar];
    self.weChatNavigationBar.titleLabel.text=@"确认订单";
    
    [self.weChatNavigationBar.leftButton setImage:[UIImage imageNamed:@"button_nav_back_a"] forState:UIControlStateNormal];
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(buttonBackAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.weChatNavigationBar.rightButton.hidden = YES;
}

- (void)buttonBackAction:(UIButton*)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)updateView {
    NSString *strPrize = [NSString stringWithFormat:@"￥%d元",[self.orderInfo ql_intForKey:@"ACTUAL_PRICE"]];
    self.labelProduct.text = [NSString stringWithFormat:@"共%@个商品%@",[self.orderInfo ql_stringForKey:@"TOTAL_NUM"],strPrize];
    
    self.addressTableViewCell.buttonOk.hidden = YES;
    self.addressTableViewCell.labelDesc.text = [self.orderInfo ql_stringForKey:@"ADDRESS"];
    self.addressTableViewCell.labelName.text = [self.orderInfo ql_stringForKey:@"CONTACT"];
    self.addressTableViewCell.labelPhone.text = [self.orderInfo ql_stringForKey:@"PHONE"];
    self.addressTableViewCell.buttonDefault.hidden = YES;
    
    self.orderDetailFootView.textFieldRemark.text = [self.orderInfo ql_hasObjectForKey:@"NOTES"]?[self.orderInfo ql_stringForKey:@"NOTES"]:@" ";
    [self.orderDetailFootView.buttonCode setTitle:@"" forState:UIControlStateNormal];
    self.orderDetailFootView.textFieldCode.text = @"";
    self.orderDetailFootView.textFieldCode.enabled = NO;
    self.orderDetailFootView.labelCount.text = [NSString stringWithFormat:@"抵￥%d元",-[self.orderInfo ql_intForKey:@"COUPON_PRICE"]];
    
    if ([self.orderInfo ql_hasObjectForKey:@"USER_COUPONS"]) {
        NSArray *arr = [self.orderInfo objectForKey:@"USER_COUPONS"];
        NSDictionary *dic = [arr firstObject];
        self.orderDetailFootView.textFieldCode.text = [dic ql_stringForKey:@"NAME"];
        [self.orderDetailFootView.buttonCode setTitle:[dic ql_stringForKey:@"NAME"] forState:UIControlStateNormal];
    }
    
    if ([[self.orderInfo ql_stringForKey:@"STATUS"] isEqualToString:@"未付款"]==NO) {
        self.buttonBuy.hidden = YES;
        self.buttonCancle.hidden = YES;
        self.labelProduct.text = [NSString stringWithFormat:@"共%@个商品%@ 订单状态:%@",[self.orderInfo ql_stringForKey:@"TOTAL_NUM"],strPrize,[self.orderInfo ql_stringForKey:@"STATUS"]];
    }else{
        self.buttonBuy.hidden = NO;
        self.buttonCancle.hidden = NO;
    }
    self.orderDetailFootView.textFieldRemark.enabled = NO;
    [self endRefresh];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    long count = self.contents==nil?0:self.contents.count;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TROrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TROrderDetailTableViewCell"];
    if (cell == nil) {
        cell = [[TROrderDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TROrderDetailTableViewCell"];
    }
    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    cell.buyCarViewController = self;
    [cell setNeedsDisplay];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TROrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRBuyCarTableViewCell"];
    if (cell == nil) {
        cell = [[TROrderDetailTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRBuyCarTableViewCell"];
    }
    NSMutableDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    return [cell getHeight];
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSMutableDictionary *dic = [self.contents objectAtIndex:indexPath.row];
    [QLPlayerManager openProductDetailWithId:[dic ql_stringForKey:@"ID"] viewController:self];
}

- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadOrderDetail];
    };
}

- (void)loadOrderDetail {
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyOrder?type=12004&userId=%@&id=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,self.orderId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        self.orderInfo = resultDic[@"USER_INFO_RSP"][@"ORDER_INFO"][0];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];

}

- (void)setOrderInfo:(NSDictionary *)orderInfo {
    _orderInfo = orderInfo;
    NSArray *arr = [self.orderInfo objectForKey:@"ORDER_ITEM"];
    [self.contents removeAllObjects];
    [self.contents addObjectsFromArray:arr];
    
    [self updateView];
}

- (IBAction)buttonCancleAction:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"确定取消此订单吗？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
    
    [alert show];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex==1) {
        [QLMaskUtil showMaskLoadingWithView:self.view];
        NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyOrder?type=12003&userId=%@&id=%@";
        URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,self.orderId];
        NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
        URLTmp = URLTmp1;
        NSLog(@"%@",URLTmp);
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
            [QLMaskUtil hideLoadingMaskWithView:self.view];
            NSString *requestTmp = [NSString stringWithString:operation.responseString];
            NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
            NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
            if ([QLPublic isSuccess:resultDic]) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [QLMaskUtil hideLoadingMaskWithView:self.view];
            NSLog(@"Failure: %@",error);
            [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
        }];
        [operation start];
    }
}

- (void)endRefresh
{
    // 刷新表格
    [self.tableView reloadData];
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
}

- (IBAction)buttonDoCashAction:(UIButton*)button {
    [QLMaskUtil showMaskLoadingWithView:self.view];
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/MyOrder?type=12005&userId=%@&id=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,self.orderId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
    NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSString *requestTmp = [NSString stringWithString:operation.responseString];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableContainers error:nil];
        if ([QLPublic isSuccess:resultDic]) {
            NSDictionary *dic = resultDic[@"USER_INFO_RSP"][@"ORDER_RESULT"];
            NSString *prepayId = [dic ql_stringForKey:@"PREPAY_ID"];
            NSString *appId = [dic ql_stringForKey:@"APPID"];
            NSString *nonceStr = [dic ql_stringForKey:@"NONCE_STR"];
            NSString *partnerId = PARTNER_ID;
            NSString *sign = [dic ql_stringForKey:@"SIGN"];
            if (prepayId==nil) {
                [SVProgressHUD showErrorWithStatus:@"预支付号获取失败!"];
                return;
            }
            [self sendPayWithPrepayId:prepayId appId:appId nonceStr:nonceStr partnerId:partnerId sign:sign];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [QLMaskUtil hideLoadingMaskWithView:self.view];
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];

}


- (NSString*)getSignWithPrepayId:(NSString*)prepayId appId:(NSString*)appId nonceStr:(NSString*)nonceStr partnerId:(NSString*)partnerId timestamp:(int)timestamp{
    //第二次签名参数列表
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    [signParams setObject: appId        forKey:@"appid"];
    [signParams setObject: @"Sign=WXPay"      forKey:@"package"];
    [signParams setObject: partnerId        forKey:@"partnerid"];
    [signParams setObject: prepayId     forKey:@"prepayid"];
    [signParams setObject: nonceStr    forKey:@"noncestr"];
    [signParams setObject: [NSString stringWithFormat:@"%d", timestamp]   forKey:@"timestamp"];
    //生成签名
    NSString *sign  = [self createMd5Sign:signParams];
    
    return sign;
}

//创建package签名
-(NSString*) createMd5Sign:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
        
    }
    //添加key字段
    [contentString appendFormat:@"key=%@", PARTNER_ID];
    //得到MD5 sign签名
    NSString *md5Sign =[WXUtil md5:contentString];
    
    return md5Sign;
}

- (void)sendPayWithPrepayId:(NSString*)prepayId appId:(NSString*)appId nonceStr:(NSString*)nonceStr partnerId:(NSString*)partnerId sign:(NSString*)sign
{
    int time = (int)[[NSDate date] timeIntervalSince1970];
    //调起微信支付
    PayReq* req             = [[PayReq alloc] init];
    req.openID              = appId;
    req.partnerId           = partnerId;
    req.prepayId            = @"wx20150816174905e9a06e5a060285133509";//prepayId;
    req.nonceStr            = @"KmkeReGmzVcW2045";//nonceStr;
    req.timeStamp           = 1439718545;//(int)time;
    req.package             = @"Sign=WXPay";
    req.sign                = @"8CD64259FAE552792A4AA925D165AD49";//[self getSignWithPrepayId:prepayId appId:appId nonceStr:nonceStr partnerId:partnerId timestamp:time];
    
    [WXApi sendReq:req];
    
    //日志输出
    NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
}

//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
}

@end
